let cookieReadBtn = document.getElementById('readCookies');
let cookieslist = document.getElementById('cookieslist');
let cookiesWrite = document.getElementById('cookiesWrite');
let cookieReadArea = document.getElementById('cookieReadArea');
let cookieLocateAdress = document.getElementById('cookieLocateAdress');
let seqWriteCheckboxArea = document.querySelector('.seq-write-checkbox-area')
let writeSEQCheckbox = document.querySelector('input[name=writeSEQ]')
let SEQValueInput = document.querySelector('input[id=SEQValue]')
cookieReadArea.style.display = 'none'

let cookieExecuteCode = `
(function () {
  let cookieStr = document.cookie
  if (!cookieStr) return {}
  let cookieStrArr = cookieStr.split(";")
  let cookieItems = {}
  for (cookieStr of cookieStrArr) {
    let itemStrArr = cookieStr.split("=")
    cookieItems[itemStrArr[0].trim()] = itemStrArr[1] && itemStrArr[1].trim()
  }
  return cookieItems
})()
`
let cookiesNeetWriteItems 
cookieReadBtn.onclick = function () {
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    chrome.tabs.executeScript(
      tabs[0].id,
      { code: cookieExecuteCode },
      function ([cookieItems]) {
        let divFrag = document.createDocumentFragment()
        cookiesNeetWriteItems = cookieItems
        for (let prop in cookieItems) {
          divFrag.appendChild(createSessionItemLi(prop, cookieItems[prop]))
          prop === 'W-SEQ' && (seqWriteCheckboxArea.style.display = 'none')
        }
        cookieslist.innerHTML = ""
        cookieslist.appendChild(divFrag)
        cookieReadArea.style.display = 'block'
      });
  });
};

cookiesWrite.onclick = function () {
  let locateVal = cookieLocateAdress.value
  if (!locateVal) {
    alert('请填写要写入cookie的地址')
    return false
  }
  chrome.tabs.getAllInWindow(function(v){
    let needWriteTab
    for (let tab of v) {
      if (tab && tab.url && tab.url.includes(locateVal)) {
        needWriteTab = tab
        break
      }
    }
    if (!needWriteTab) return false
    writeCookie(needWriteTab)
    alert('cookie写入' + locateVal + '成功！')

  })
}

function writeCookie (needWriteTab) {
  let hasSEQProp = false
  for (let prop in cookiesNeetWriteItems) { 
    prop === 'W-SEQ' && (hasSEQProp = true)
    chrome.tabs.executeScript(
      needWriteTab.id,
      { code: `document.cookie="${prop}=${cookiesNeetWriteItems[prop]}; path=/"` },
      function (arg) {
        console.log(prop + '写入成功！',arg)
    });
  }
  if (!hasSEQProp && writeSEQCheckbox.checked ) {
    chrome.tabs.executeScript(
      needWriteTab.id,
      { code: `document.cookie="W-SEQ=${SEQValueInput.value}; path=/"` },
      function (arg) {
        console.log(prop + '写入成功！',arg)
    });
    chrome.tabs.executeScript(
      needWriteTab.id,
      { code: `document.cookie="W-FLOW=canary; path=/"` },
      function (arg) {
        console.log(prop + '写入成功！',arg)
    });
  }
}